package la.renzhen.rtpt.config.source;

import la.renzhen.rtpt.config.ConfigurationSource;
import redis.clients.jedis.Jedis;

import java.util.*;

/**
 * <p>
 *
 * @author <a href="mailto:zhouhaichao@2008.sina.com">haiker</a>
 * @version 30/05/2018 12:06 AM
 */
public class RedisConfigurationSource implements ConfigurationSource {

    String module;
    Jedis jedis;

    public RedisConfigurationSource(String module, Jedis jedis) {
        this.module = module;
        this.jedis = jedis;
    }

    @Override
    public Map<String, String> loadAll(String environment, String prefix) {
        prefix = Optional.ofNullable(prefix).orElse("");
        String redisPattern = String.format("%s:%s:%s*", module, environment, prefix);
        int length = String.format("%s:%s:", module, environment).length();
        Map<String, String> values = new HashMap<>();
        Set<String> keySets = jedis.keys(redisPattern);
        if (keySets.isEmpty()) {
            return values;
        }

        String[] keys = new String[keySets.size()];
        Iterator<String> it = keySets.iterator();
        for (int i = 0; i < keySets.size(); i++) {
            keys[i] = it.next();
        }

        List<String> valueList = jedis.mget(keys);
        int i = 0;
        for (String key : keys) {
            String rkey = key.substring(length);
            String value = valueList.get(i++);
            values.put(rkey, value);
        }
        return values;
    }

    @Override
    public String get(String environment, String key) {
        String redisKey = String.format("%s:%s:%s", module, environment, key);
        return jedis.get(redisKey);
    }
}
